package main;

import java.io.*;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

@ManagedBean
@SessionScoped
public class Login 
implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2435679669081716438L;
	private boolean isLoggedIn;  
	String type = null;

	public String login(User user) {
		DaoUsers daoU = new DaoUsers();

		String name = user.getUsername();
		String password = user.getPassword();

		try {
			type = daoU.getUserType(name, password);
		} catch (SQLException e) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage("Login", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username o password errati", "Username o password errati"));
			type = null;
		}

		return type;
	}


	/** 
	 * An event listener for redirecting the user to login page if he/she is not currently logged in 
	 * @param event 
	 */  
	public void verifyUseLogin(ComponentSystemEvent event){  
		if(!isLoggedIn){  
			doRedirect(type);  
		}  
	}  

	/** 
	 * Method for redirecting a request 
	 * @param url 
	 */  
	private void doRedirect(String url){  
		try {  
			FacesContext context=FacesContext.getCurrentInstance();  
			context.getExternalContext().redirect(type);  
		} catch (IOException e) {  
			e.printStackTrace();  
		}  
	}  
}
